package com.gh.reggie.filter;

import com.alibaba.fastjson.JSON;
import com.gh.reggie.common.BaseContext;
import com.gh.reggie.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 检查用户是否登录
 */

@WebFilter(filterName = "loginCheckFilter",urlPatterns = "/*")
@Slf4j
public class LoginCheckFilter  implements Filter {


    //路径匹配器，支持通配符
    public static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();


    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;


        //1.获取本次请求的URL
        String requestURI = request.getRequestURI();
        String[] urls = new String[]{
                "/employee/login",
                "/employee/logout",
                "/backend/**",
                "/front/**",
                "/common/**",
                "/user/sendMsg",
                "/user/login",
        };

        log.info("拦截的的URI为：{}",requestURI);

        //2.判断本次请求是否需要处理
        boolean check = check(urls, requestURI);


        //3.如果不需要处理，则直接放行
        if(check){
            log.info("本次请求{}不需要处理",requestURI);
            filterChain.doFilter(request,response);
            return;
        }




        //4-1. 服务端判断登陆状态，根据session中的消息进行判断
        //如果employee中的值不为空的话就是表示已登录，则直接放行
        if(request.getSession().getAttribute("employee") != null){
            log.info("用户以登录，时登录的用户为{}",request.getSession().getAttribute("employee"));

            //获取线程id名，确认是否在同一线程
            /*Long id = Thread.currentThread().getId();*/
            log.info("线程id为{}",Thread.currentThread().getId());
            Long empId = (Long) request.getSession().getAttribute("employee");
            //在该线程中设置id
            BaseContext.setCurrentId(empId);

            //放行
            filterChain.doFilter(request,response);
            return;
        }

        // 4-2、 移动端(消费者端)登录状态(session中含有user的登录信息)，如果已经登录，则直接放行
        Long userId = (Long) request.getSession().getAttribute("user");
        if (userId != null) {
            log.info("用户已经登录，用户id为:{}", userId);
            // 自定义元数据对象处理器 MyMetaObjectHandler中需要使用 登录用户id
            //   通过ThreadLocal set和get用户id
            BaseContext.setCurrentId(userId);
            filterChain.doFilter(request, response);
            return;
        }


        log.info("用户未登录");
        //5.如果未登录则直接返回未登录结果
        response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));




     /*   //{}在此处是表示占位符，
        log.info("拦截到请求：{}",request.getRequestURI());
        //放行
        filterChain.doFilter(request,response);*/

    }

    /**
     * 判断拦截路径是否需要放行:将request的页面match匹配设置的urls路径
     * @param requestURI
     * @return
     */
    public boolean check(String[] urls,String requestURI){
        for (String url : urls) {
            boolean match = PATH_MATCHER.match(url, requestURI);
            if(match){
                return true;
            }
        }
        return false;
    }
}
